<?php
/**
 * 首页商品列表
 * Created by PhpStorm.
 * User: Jmashimaro
 * Date: 2015/1/20
 * Time: 13:34
 */

class IndexApp extends MallbaseApp {


    /**
     * 首页列表
     * @author jiayanxiu
     * @date 2015/07/17
     */
    public function index() {
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'GET') {
            $this->ajax_return(FLAG_ERROR, '非法操作！');
        }

        $offset = $this->get_gp('offset', 'G');
        $size = $this->get_gp('size', 'G');
        $size = $size ? intval($size) : 10;
        $offset = $offset ? intval($offset) : 0;
        $model = m('goods');
        $user_id = $this->checkLogin();
        if ($user_id) {//已经登陆
            //如果刚注册的用户没有关注店铺，则默认让其它关注几个商铺
            $mod_collect = m('collect');
            $sql = "SELECT item_id FROM ".DB_PREFIX."collect WHERE user_id={$user_id} AND `type`='store' LIMIT 1";
            $row = $mod_collect->getRow($sql);
            if (!$row) {
                //没关注店铺
                $data = $this->getPopularList();
                if ($data) {
                    $this->ajax_return(FLAG_OTHER, '', $data);
                } else {
                    $this->ajax_return(FLAG_ERROR, '没有更多数据！');
                }
            } else {
                /*三个表结合查询*/
                $sql = 'SELECT item_id FROM '.DB_PREFIX."collect WHERE user_id={$user_id} AND type='store'";
                $sql = 'SELECT g.goods_id,g.goods_name,g.introduction,g.default_image,g.price,g.discount_price,g.is_act,
                        s.store_name,s.store_logo,s.brand_describe,s.store_id,gs.collects,gs.base_collects,
                        gs.comments as `count`,g.market_price,g.is_act,g.detail_url,g.source FROM '.DB_PREFIX.'goods AS g
                        LEFT JOIN '.DB_PREFIX.'store AS s ON g.store_id=s.store_id LEFT JOIN '.DB_PREFIX.'goods_statistics gs
                        ON gs.goods_id=g.goods_id WHERE g.store_id IN ('.$sql.") AND g.if_examine = 1 AND g.if_finance = 1
                        AND g.if_show = 1 AND g.closed = 0 ORDER BY gs.views DESC,g.last_update DESC LIMIT {$offset},{$size}";
                $data = $model->getAll($sql);
                //查询这个用户喜欢的商品
                $sql = 'SELECT item_id FROM '.DB_PREFIX."collect WHERE user_id={$user_id} AND type='goods'";
                $goods = $model->getAll($sql);
                $goodsArr = array();
                foreach($goods as $key => $value){
                    $goodsArr[] = $value["item_id"];
                }
            }
            if ($data) {
                $domain = get_domain();
                foreach ($data as $key=>$val) {
                    if ($user_id) {
                        $val['follow'] = in_array($val['goods_id'],$goodsArr) ? "1" : "0";
                    } else {
                        $val['follow'] = 0;
                    }
                    if ($val['discount_price'] && $val['is_act'] == 1 && $val['discount_price'] < $val['price']) {
                        $val['discount'] = 1;//有折扣价
                    } else {
                        $val['discount'] = 0;//无折扣价
                    }
                    if (strpos($val['default_image'], FARFETCH_URL) === false) {
                        $val['default_image'] = $val['default_image'] ? QINIU_URL.$val['default_image'].GOODS_IMG : $domain.'/'.Conf::get('default_goods_image');
                    }
                    $val['collects'] = $val['collects'] + $val['base_collects'];
                    $val['store_logo'] = $val['store_logo'] ? QINIU_URL.$val['store_logo'].STORE_LOGO : '';
                    $val['introduction'] = stripslashes($val['introduction']);
                    //查询出商品的库存数
                    $sql = "SELECT SUM(`stock`) AS total_stock FROM ".DB_PREFIX."goods_spec WHERE goods_id={$val['goods_id']}";
                    $tmp = $model->getRow($sql);
                    $val['allstock'] = $tmp['total_stock'] ? intval($tmp['total_stock']) : 0;
                    //查询出商品的图片信息
                    $sql = 'SELECT image_id,thumbnail,image_url FROM '.DB_PREFIX."goods_image
                        WHERE goods_id={$val['goods_id']} ORDER BY image_id ASC LIMIT 0,10";
                    $info = $model->getAll($sql);
                    if ($info) {
                        foreach ($info as $k=>$v) {
                            if (strpos($v['thumbnail'], FARFETCH_URL) === false) {
                                $v['thumbnail'] = $v['thumbnail'] ? QINIU_URL.$v['thumbnail'].GOODS_IMG : '';
                            }
                            if (strpos($v['thumbnail'], FARFETCH_URL) === false) {
                                $v['image_url'] = $v['image_url'] ? QINIU_URL.$v['image_url'].GOODS_IMG : '';
                            }
                            $info[$k] = $v;
                        }
                        $val['image'] = $info;
                    } else {
                        $val['image'] = array();
                    }
                    $data[$key] = $val;
                }
                //只有第一页之内显示显示
                if ($offset == 0) {
                    $tmp = array();
                    $tmp = $this->mode();
                    $data = array_merge(array($tmp), $data);
//                    shuffle($list);
                }
            }
            //返回已经登陆的状态
            $this->ajax_return(FLAG_OK, '', $data);

        } else {//没有登陆
            $list = array();
            /**只查询了goods表和store表**/
            $domain = get_domain().'/';
            $sql = "SELECT store_id,store_name,store_logo,brand_describe FROM (SELECT a.store_id,a.store_name,a.store_logo,a.brand_describe
                    FROM ".DB_PREFIX."store a LEFT JOIN ".DB_PREFIX."goods b
                    ON a.store_id = b.store_id WHERE b.if_examine = 1 AND b.if_finance = 1 AND b.if_show = 1 AND b.closed = 0
                    GROUP BY a.store_id ORDER BY collects DESC) s LIMIT {$offset},{$size}";
            $data = $model->getAll($sql);
            if ($data) {
                foreach ($data as $key=>$val) {
                    $val['store_logo'] = $val['store_logo'] ? QINIU_URL.$val['store_logo'] : $domain.Conf::get('default_goods_image');
                    $sql = "SELECT goods_id,goods_name,price,introduction,default_image,detail_url,source
                        FROM ".DB_PREFIX."goods WHERE store_id={$val['store_id']} AND if_examine = 1 AND if_finance = 1
                        AND if_show = 1 AND closed = 0 ORDER BY last_update DESC,add_time DESC LIMIT 5";
                    $goods = $model->getAll($sql);
                    if ($goods) {
                        foreach ($goods as $k=>$v) {
                            if (strpos($v['default_image'], FARFETCH_URL) === false) {
                                $v['default_image'] = $v['default_image'] ? QINIU_URL.$v['default_image'].GOODS_IMG : $domain.Conf::get('default_goods_image');
                            }
                            $v['introduction'] = stripslashes($v['introduction']);
                            $v['goods_name'] = stripslashes($v['goods_name']);
                            $goods[$k]=$v;
                        }
                        $val['goods'] = $goods;
                        $list[] = $val;
                    }
                }
                //只有第一页之内显示显示
                if ($offset == 0) {
                    $tmp = array();
                    $tmp = $this->mode();
                    $list = array_merge(array($tmp), $list);
//                    shuffle($list);
                }
            }
            //返回未登陆的状态
            $this->ajax_return(FLAG_ANOTHER, '', $list);
        }
    }


    /**
     * 用户在刚登陆软件时，如果没有关注店铺，则让其关注商铺
     * @return array
     * @author jiayanxiu
     * @date 2015/04/28
     */
    private function getPopularList() {
        $domain = get_domain().'/';
        $model = m('store');
        $sql = "SELECT s.store_id,s.store_name,s.store_logo FROM ".DB_PREFIX."store s LEFT JOIN ".DB_PREFIX."goods g
                ON s.store_id = g.store_id WHERE s.state=1 AND g.if_examine = 1 AND g.if_finance = 1 AND g.if_show = 1
                AND g.closed = 0 GROUP BY s.store_id ORDER BY s.sort_order DESC,s.collects DESC LIMIT 30";
        $data = $model->getAll($sql);
        if ($data) {
            foreach ($data as $key=>$val) {
                $data[$key]['store_logo'] = $val['store_logo'] ? QINIU_URL.$val['store_logo'] : $domain.Conf::get('default_goods_image');
                $sql = "SELECT goods_id,goods_name,price,introduction,default_image,detail_url,source
                        FROM ".DB_PREFIX."goods WHERE store_id={$val['store_id']} AND if_examine = 1 AND if_finance = 1
                        AND if_show = 1 AND closed = 0 ORDER BY last_update DESC,add_time DESC LIMIT 5";
                $goods = $model->getAll($sql);
                if ($goods) {
                    foreach ($goods as $k=>$v) {
                        if (strpos($v['default_image'], FARFETCH_URL) === false) {
                            $v['default_image'] = $v['default_image'] ? QINIU_URL.$v['default_image'] : $domain.Conf::get('default_goods_image');
                        }
                        $v['introduction'] = stripslashes($v['introduction']);
                        $v['goods_name'] = stripslashes($v['goods_name']);
                        $goods[$k]=$v;
                    }
                    $data[$key]['goods'] = $goods;
                }else{//删除没有分类商品的店铺
                    unset($data[$key]);
                }

            }
        }
        $data = array_merge(array(), $data);
        return $data;
    }


    /**
     * 首页列表，1.1版本正在使用
     * @author jiayanxiu
     * @date 2015/07/17
     */
    public function run() {
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'GET') {
            $this->ajax_return(FLAG_ERROR, '非法操作！');
        }

        $page = $this->get_gp('page', 'G');
        $size = $this->get_gp('size', 'G');
        $size = $size ? intval($size) : 10;
        $offset = $page > 1 ? ($page - 1) * $size : 0;
        //获取三种模式
        $data = $this->module($offset);
        $this->ajax_return(FLAG_OK, '', $data);
    }


    /**
     * 首页展示三种模式
     * @param $offset
     * @return array|bool
     * @author jyx
     * @date 2015/10/15
     */
    private function module($offset) {
        $data = $list = $goods = $store = $recommend = array();
        $model = m('goods');
        //暂留一个广告模式，第0个模式

        $tmp = array(
            array(
                'subject' => '加入He She将获得：',
                'titles' => '全球购、国际品牌的商品',
                'module' => 0,
            ),
        );
        //单品模块
        //查询出商品的总数
        $sql = "SELECT g.goods_id,g.default_image,g.detail_url,g.source,SUM(gs.collects+gs.base_collects) AS collects
            FROM ".DB_PREFIX."goods g LEFT JOIN ".DB_PREFIX."goods_statistics gs ON g.goods_id=gs.goods_id
            WHERE g.if_examine = 1 AND g.if_finance = 1 AND g.if_show = 1 AND g.closed = 0 GROUP BY goods_id
            ORDER BY collects DESC LIMIT {$offset},8";
        $goods = $model->getAll($sql);

        if ($goods) {
            foreach ($goods as $key=>$val) {
                $val['module'] = 1;
                if (strpos($val['default_image'], FARFETCH) === false) {
                    $val['default_image'] = $val['default_image'] ? QINIU_URL.$val['default_image'] : '';
                }
                if ($key == 0) {
                    $list[$key] = $val;
                } else {
                    $goods[$key] = $val;
                }
            }
        }
        //店铺模块
        //获取商铺信息
        $sql = "SELECT store_id,store_name,store_logo FROM ".DB_PREFIX."store WHERE state = 1
                ORDER BY collects DESC LIMIT {$offset},1";
        $store = $model->getAll($sql);
        if ($store) {
            foreach($store as $key=>$val) {
                $val['module'] = 2;
                $val['logo'] = $val['logo'] ? QINIU_URL.$val['logo'] : '';
                //获取商铺下的商品信息
                $sql = "SELECT goods_id,goods_name,introduction,default_image,price,detail_url,source
                FROM ".DB_PREFIX."goods WHERE store_id={$val['store_id']} AND if_examine=1 AND if_finance=1
                AND if_show=1 AND closed = 0 ORDER BY last_update DESC LIMIT 5";
                $goodsInfo = $model->getAll($sql);
                if ($goodsInfo) {
                    foreach ($goodsInfo as $k=>$v) {
                        if (strpos($v['default_image'], FARFETCH) === false) {
                            $v['default_image'] = $v['default_image'] ? QINIU_URL.$v['default_image'] : '';
                        }
                        $goodsInfo[$k] = $v;
                    }
                }
                $val['goods'] = $goodsInfo;
                $store[$key] = $val;
            }
        }

        //专题模块
        //获取专题信息
        $sql = "SELECT recom_id,recom_name,recom_title,recom_content,`type`,video_link,recom_image
                FROM ".DB_PREFIX."recommend ORDER BY recom_id DESC LIMIT {$offset},1";
        $recommend = $model->getAll($sql);
        if ($recommend) {
            foreach ($recommend as $key=>$val) {
                $val['module'] = 3;
                //查询出这条推荐下商品的goods_id
                $sql = "SELECT g.goods_id,g.store_id,g.goods_name,g.introduction,g.default_image,g.price,g.source
                    FROM ".DB_PREFIX."recommend_goods rg LEFT JOIN ".DB_PREFIX."goods g ON rg.goods_id=g.goods_id
                    WHERE rg.recom_id={$val['recom_id']} ORDER BY rg.goods_id DESC LIMIT 5";
                $recomGoods = $model->getAll($sql);
                foreach ($recomGoods as $k => $v) {
                    //如果是farfetch商品
                    if (strpos($v['default_image'], FARFETCH_URL) === false) {
                        $v['default_image'] = $v['default_image'] ? QINIU_URL.$v['default_image'].DISCOVERY_GOODS_IMG : '';
                    }
                    $recomGoods[$k] = $v;
                }
                $val['goods'] = $recomGoods;
                $recommend[$key] = $val;
            }
        }

        $data = array_merge($goods, $store, array($recommend));
        shuffle($data);
        $data = array_merge($tmp, $list, $data);
        return $data;
    }

    /**
     * 首页四种展现形式
     * @author jyx
     * @date 2015/08/20
     */
    private function mode() {
        $mode = mt_rand(1, 4);
//        $mode = 2;
        $data = array();
//        $uri = getUrlByEnv ( "index.php?c=activity&a=mint" );
        $uri = '';
        $model = m('goods');
        switch ($mode) {
            case 1://单品
//                $goods_id = 3170;
                $goods_id = 0;
                if ($goods_id) {//查询指定的商品
                    $sql = "SELECT goods_id,default_image,detail_url,source FROM " . DB_PREFIX . "goods WHERE goods_id={$goods_id}";
                } else {//查询出随机的商品
                    //查询出商品的总数
                    $sql = "SELECT COUNT(*) AS num FROM ".DB_PREFIX."goods WHERE if_examine = 1 AND if_finance = 1
                        AND if_show = 1 AND closed = 0 ORDER BY goods_id DESC";
                    $tmp = $model->getRow($sql);
                    $offset = mt_rand(0, $tmp['num'] - 1);
                    $sql = "SELECT goods_id,default_image,detail_url,source FROM ".DB_PREFIX."goods WHERE if_examine = 1
                        AND if_finance = 1 AND if_show = 1 AND closed = 0 ORDER BY goods_id DESC LIMIT {$offset},1";
                }
                $data = $model->getRow($sql);
                if ($data) {
                    //如果是farfetch商品
                    if (strpos($data['default_image'], FARFETCH_URL) === false) {
                        $data['default_image'] = QINIU_URL.$data['default_image'].GOODS_IMG;
                    }
                    $data['if_show'] = 1;
                    $data['subject'] = '加入He She将获得：';
                    $data['titles'] = '全球购、国际品牌的商品';
                    $data['uri'] = $uri;
                } else {
                    $data['if_show'] = 0;
                }
                break;
            case 2://商铺banner加小商品
//                $store_id = 112294;
                $store_id = 0;
                if ($store_id) {//查询出指定的商铺
                    $sql = "SELECT g.goods_id,g.goods_name,g.introduction,g.default_image,g.price,g.detail_url,g.source,
                        s.store_id,s.iphone_banner FROM ".DB_PREFIX."goods g LEFT JOIN ".DB_PREFIX."store s ON
                        g.store_id=s.store_id WHERE s.store_id={$store_id} ORDER BY g.goods_id DESC LIMIT 5";
                } else {//随机出一个商铺的id
                    $sql = "SELECT COUNT(*) AS num FROM ".DB_PREFIX."store WHERE state=1";
                    $tmp = $model->getRow($sql);
                    $offset = mt_rand(0, $tmp['num'] - 1);
                    $sql = "SELECT store_id FROM ".DB_PREFIX."store WHERE state=1 ORDER BY store_id DESC LIMIT {$offset}, 1";
                    $temp = $model->getRow($sql);
                    $sql = "SELECT g.goods_id,g.goods_name,g.introduction,g.default_image,g.price,g.detail_url,g.source,
                        s.store_id,s.iphone_banner FROM ".DB_PREFIX."goods g LEFT JOIN ".DB_PREFIX."store s
                        ON g.store_id=s.store_id WHERE s.store_id={$temp['store_id']} AND g.if_examine=1 AND g.if_finance=1
                        AND g.if_show = 1 AND g.closed = 0 ORDER BY g.goods_id DESC LIMIT 5";
                }
                $tmps = $model->getAll($sql);
                if ($tmps) {
                    foreach ($tmps as $key=>$val) {
                        $data['store_id'] = $val['store_id'];
                        $data['iphone_banner'] = $val['iphone_banner'];
                        unset($val['store_id'],$val['iphone_banner']);
                        //如果是farfetch商品
                        if (strpos($val['default_image'], FARFETCH_URL) === false) {
                            $val['default_image'] = QINIU_URL.$val['default_image'].GOODS_S_IMG;
                        }
                        $data['goods'][] = $val;
                    }
                    $data['subject'] = '今日风范  He She 真挚推荐';
                    $data['titles'] = '今日风范  He She 真挚推荐';
                    $data['if_show'] = 1;
                    $data['uri'] = $uri;
                } else {
                    $data['if_show'] = 0;
                }
                break;
            case 3://商铺logo，商品图片，商品金额
//                $goods_id = 3170;
                $goods_id = 0;
                if ($goods_id) {//查询出指定的商品
                    $sql = "SELECT g.goods_id,g.goods_name,g.price,g.default_image,g.introduction,g.detail_url,g.source,
                            gs.collects,gs.base_collects,s.store_id,s.store_name,s.store_logo FROM ".DB_PREFIX."goods g
                            LEFT JOIN ".DB_PREFIX."store s ON s.store_id=g.store_id LEFT JOIN ".DB_PREFIX."goods_statistics gs
                            ON g.goods_id=gs.goods_id WHERE g.goods_id={$goods_id}";
                } else {//查询出随机的商品
                    $sql = "SELECT COUNT(*) AS num FROM ".DB_PREFIX."goods WHERE if_examine = 1 AND if_finance = 1
                            AND if_show = 1 AND closed = 0 ORDER BY goods_id DESC";
                    $tmp = $model->getRow($sql);
                    $offset = mt_rand(0, $tmp['num'] - 1);
                    $sql = "SELECT g.goods_id,g.goods_name,g.price,g.default_image,g.introduction,g.source,gs.collects,
                            gs.base_collects, s.store_id,s.store_name,store_logo FROM ".DB_PREFIX."goods g
                            LEFT JOIN ".DB_PREFIX."store s ON s.store_id=g.store_id LEFT JOIN ".DB_PREFIX."goods_statistics gs
                            ON g.goods_id=gs.goods_id WHERE g.if_examine=1 AND g.if_finance=1 AND g.if_show=1
                            AND g.closed = 0 ORDER BY g.goods_id DESC LIMIT {$offset},1";
                }
                $data = $model->getRow($sql);
                if ($data) {
                    if (strpos($data['default_image'], FARFETCH_URL) === false) {
                        $data['default_image'] = $data['default_image'] ? QINIU_URL.$data['default_image'] : '';
                    }
                    $data['collects'] = intval($data['collects'] + $data['base_collects']);
                    $data['if_show'] = 1;
                    $data['subject'] = '今日风范  He She 真挚推荐';
                    $data['titles'] = '今日风范  He She 真挚推荐';
                    $data['uri'] = $uri;
                } else {
                    $data['if_show'] = 0;
                }
                break;
            case 4://商铺Logo,商品小图片
//                $store_id = 88206;
                $store_id = 0;
                if ($store_id) {//查询出指定的商铺
                    $sql = "SELECT g.goods_id,g.goods_name,g.introduction,g.default_image,g.price,g.detail_url,g.source,
                        s.store_name,s.store_logo,s.store_id FROM ".DB_PREFIX."goods g LEFT JOIN ".DB_PREFIX."store s
                        ON g.store_id=s.store_id WHERE s.store_id={$store_id} ORDER BY g.goods_id DESC LIMIT 5";
                } else {//随机出一个商铺的id
                    $sql = "SELECT COUNT(*) AS num FROM ".DB_PREFIX."store WHERE state=1";
                    $tmp = $model->getRow($sql);
                    $offset = mt_rand(0, $tmp['num'] - 1);
                    $sql = "SELECT store_id FROM ".DB_PREFIX."store WHERE state=1 ORDER BY store_id DESC LIMIT {$offset}, 1";
                    $temp = $model->getRow($sql);
                    $sql = "SELECT g.goods_id,g.goods_name,g.introduction,g.default_image,g.price,g.detail_url,g.source,
                        s.store_id,s.store_name,s.store_logo FROM ".DB_PREFIX."goods g LEFT JOIN ".DB_PREFIX."store s
                        ON g.store_id=s.store_id WHERE s.store_id={$temp['store_id']} AND g.if_examine=1 AND g.if_finance=1
                        AND g.if_show=1 AND g.closed = 0 ORDER BY g.goods_id DESC LIMIT 5";
                }
                $tmps = $model->getAll($sql);
                if ($tmps) {
                    foreach ($tmps as $key=>$val) {
                        $data['store_id'] = $val['store_id'];
                        $data['store_name'] = $val['store_name'];
                        $data['store_logo'] = QINIU_URL.$val['store_logo'];
                        unset($val['store_id']);
                        //如果是farfetch商品
                        if (strpos($val['default_image'], FARFETCH_URL) === false) {
                            $val['default_image'] = QINIU_URL.$val['default_image'].GOODS_S_IMG;
                        }
                        $data['goods'][] = $val;
                    }
                    $data['if_show'] = 1;
                } else {
                    $data['if_show'] = 0;
                }
                break;
            case 5://专题模块
                //查询出最新的推荐内容
                $sql = "SELECT recom_id,recom_name,recom_title,recom_content,`type`,video_link,recom_image FROM ".DB_PREFIX."recommend ORDER BY recom_id DESC LIMIT 1";
                $data = $model->getRow($sql);
                if ($data) {
                    //查询出这条推荐下商品的goods_id
                    $sql = "SELECT g.goods_id,g.store_id,g.goods_name,g.introduction,g.default_image,g.price,g.source
                            FROM ".DB_PREFIX."recommend_goods rg LEFT JOIN ".DB_PREFIX."goods g ON rg.goods_id=g.goods_id
                            WHERE rg.recom_id={$data['recom_id']} ORDER BY rg.goods_id DESC LIMIT 5";
                    $goods = $model->getAll($sql);
                    foreach ($goods as $key=>$val) {
                        //如果是farfetch商品
                        if (strpos($val['default_image'], FARFETCH_URL) === false) {
                            $val['default_image'] = $val['default_image'] ? QINIU_URL.$val['default_image'].DISCOVERY_GOODS_IMG : '';
                        }
                        $goods[$key] = $val;
                    }
                    $data['iphone_banner'] = $data['recom_image'];
                    $data['goods'] = $goods;
                    $data['if_show'] = 1;
                    $data['subject'] = '今日风范  He She 真挚推荐';
                    $data['titles'] = '今日风范  He She 真挚推荐';
                } else {
                    $data['if_show'] = 0;
                }
                break;
        }
        $data['mode'] = $mode;
        return $data;
    }







}

